#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>

int count=0;

pthread_once_t my_init_mutex = PTHREAD_ONCE_INIT;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

void init_app(void){
	printf("invoke init_app \n");
}

void * mythread(int* penable_lock){
	int enable_lock=(int)penable_lock;
//	printf("para %d\n",enable_lock);
	
	pthread_t me=pthread_self();
	pthread_once(&my_init_mutex,init_app);
	if(enable_lock)
		assert(pthread_mutex_lock(&mutex)==0);	
	count+=count;
	printf("thread data %i , at %x\n",count++,(int)me);	
	//try let somebody change it
	sleep(1);
	printf("after sleep thread data %i , at %x\n",count++,(int)me);	
	if(enable_lock)
		assert(pthread_mutex_unlock(&mutex)==0);
	pthread_exit(NULL);
}
int main(){
	int ret;
	pthread_t thread;
	int i;
	int enable_lock=0;
	for(i=0;i<10;i++){
		ret=pthread_create(&thread,NULL,mythread,(void*)(enable_lock));
	}
	pthread_join(thread,NULL);
		
	count=0;
	enable_lock=1;
	for(i=0;i<10;i++){
		ret=pthread_create(&thread,NULL,mythread,(void*)(enable_lock));
	}
	pthread_join(thread,NULL);
	/*
	if(ret!=0){
		printf("can't cateate thread %s\n",strerror(errno));
		exit(-1);
	}
	*/
	//sleep(3);
	pthread_mutex_destroy(&mutex);

	return 0;
}